<template>
  <div style="width: 100%; height: 100%">
    <!-- <button
      @click="onClick"
      style="
        width: 100%;
        height: 100%;
        text-align: center;
        color: #000;
        background: #ffd591;
        border: 2px solid #ffa940;
        border-radius: 4px;
      "
    >
      <el-icon><Menu /></el-icon>查看更多
    </button> -->
    <el-button type="primary" size="default" @click="addEntity"
      >添加实体
    </el-button>
    <!-- 给容器添加响应式 -->
    <div id="container" ref="containerRef"></div>
    <TeleportContainer />
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { Graph, Markup } from '@antv/x6'
import { register, getTeleport } from '@antv/x6-vue-shape'
import { Dnd } from '@antv/x6-plugin-dnd'
import ProgressNode from './components/ProgressNode.vue'
// 引入 Element Plus 的图标组件
// const { Delete } = ElementPlusIconsVue
var MainColor = '#E4F3FF' //定义主题色
var SubColor = '#FFE8E8' //定义次要颜色

// 响应式获取dom节点
const containerRef = ref(null)
// 定义graph实例
const graph = ref(null)
const dnd = ref(null)
// 抽离实例化拖拽库
const initGraph = () => {
  graph.value = new Graph({
    // container: document.getElementById('container'),
    container: containerRef.value,
    width: 800,
    height: 600,
    // 背景
    background: {
      color: MainColor
    },
    // 网格
    grid: {
      visible: true,
      size: 15,
      type: 'doubleMesh',
      args: [
        {
          color: '#fff', //   主网格线颜色
          thickness: 2 // 主网格线宽度
        },
        {
          color: '#ddd', // 次网格线颜色
          thickness: 5, // 次网格线宽度
          factor: 10 // 主次网格线间隔
        }
      ]
    },
    // panning: true, //使用默认方式
    panning: {
      enabled: true, //是否开启平移
      modifiers: ['ctrl'], // 限制平移的快捷键
      eventTypes: ['leftMouseDown'], //平移的触发方式
      mousewheel: true
    },
    // mousewheel: true,  //使用默认方式
    mousewheel: {
      enabled: true, //是否开启滚轮缩放
      global: false, //是否开启全局缩放
      factor: 1.2, //缩放比例
      zoomAtMousePosition: true, //缩放时是否固定在鼠标位置
      modifiers: ['ctrl'] //限制缩放的快捷键
      // guard (e) {
      //   // 判断一个滚轮事件是否应该被处理
      //   if (e.altKey) {
      //     console.log('🚀 ~ guard ~ e.altKey:', e.altKey)
      //     // 当按下 alt 键时，忽略所有滚动事件
      //     return false
      //   }
      //   return true
      // }
    },
    connecting: {
      createEdge () {
        return this.createEdge({
          shape: 'custom-edge'
        })
      }
    },
    onEdgeLabelRendered: args => {
      const { selectors } = args
      const content = selectors.foContent
      // 渲染一个HTML节点

      if (content) {
        const ICON = document.createElement('div')
        // ICON.className = 'el-icon-delete'
        // 设置图标组件
        ICON.innerHTML = '<img src="../../assets/vue.svg" alt="Vue Logo"/>'

        ICON.onclick = onClick
        content.appendChild(ICON)
        // 使用getTeleport来创建一个可以渲染Vue组件的容器
        // const teleport = getTeleport({
        //   component: ProgressNode
        // })
        // content.appendChild(teleport)
      }
    }
  })
  graph.value.resize(800, 600) // resize 画布大小
  graph.value.centerContent() // 将画布中元素居中展示
  dnd.value = new Dnd({
    target: graph.value // 目标画布
  })
  addNode()
  graph.value.addNode({
    shape: 'custom-vue-node',
    x: 100,
    y: 60
  })
}
// 注册节点
Graph.registerNode(
  'custom-node',
  {
    inherit: 'rect', // 继承于 rect 节点
    width: 100,
    height: 40,
    label: '节点',
    markup: [
      {
        tagName: 'rect', // 标签名称
        selector: 'body' // 选择器
      },
      {
        tagName: 'image',
        selector: 'img'
      },
      {
        tagName: 'text',
        selector: 'label'
      }
    ],
    attrs: {
      body: {
        stroke: '#8f8f8f',
        strokeWidth: 1,
        fill: '#fff',
        rx: 6,
        ry: 6
      },
      img: {
        'xlink:href':
          'https://gw.alipayobjects.com/zos/antfincdn/FLrTNDvlna/antv.png',
        width: 16,
        height: 16,
        x: 12,
        y: 12
      }
    },
    // 注册桩
    ports: {
      groups: {
        left: {
          position: 'left',
          attrs: {
            circle: {
              magnet: true,
              stroke: '#8f8f8f',
              r: 5
            }
          }
        },
        right: {
          position: 'right',
          attrs: {
            circle: {
              magnet: true,
              stroke: '#8f8f8f',
              r: 5
            }
          }
        }
      },
      // 使用桩
      items: [
        {
          id: 'port_1',
          group: 'left'
        },
        {
          id: 'port_2',
          group: 'right'
        }
      ]
    }
  },
  true
)
// 注册边
Graph.registerEdge(
  'custom-edge',
  {
    inherit: 'edge',
    // markup: [
    //   {
    //     tagName: 'path',
    //     selector: 'shadow',
    //     attrs: {
    //       fill: 'none'
    //     }
    //   },
    //   {
    //     tagName: 'path',
    //     selector: 'line',
    //     attrs: {
    //       fill: 'none',
    //       cursor: 'pointer'
    //     }
    //   }
    // ],
    // attrs: {
    //   line: {
    //     connection: true,
    //     stroke: '#dddddd',
    //     strokeWidth: 20,
    //     strokeLinejoin: 'round',
    //     targetMarker: {
    //       name: 'path',
    //       stroke: 'none',
    //       d: 'M 0 -10 -10 0 0 10 z',
    //       offsetX: -5
    //     },
    //     sourceMarker: {
    //       name: 'path',
    //       stroke: 'none',
    //       d: 'M -10 -10 0 0 -10 10 0 10 0 -10 z',
    //       offsetX: -5
    //     }
    //   },
    //   shadow: {
    //     connection: true,
    //     refX: 3,
    //     refY: 6,
    //     stroke: '#000000',
    //     strokeOpacity: 0.2,
    //     strokeWidth: 20,
    //     strokeLinejoin: 'round',
    //     targetMarker: {
    //       name: 'path',
    //       d: 'M 0 -10 -10 0 0 10 z',
    //       stroke: 'none',
    //       offsetX: -5
    //     },
    //     sourceMarker: {
    //       name: 'path',
    //       stroke: 'none',
    //       d: 'M -10 -10 0 0 -10 10 0 10 0 -10 z',
    //       offsetX: -5
    //     }
    //   }
    // }
    defaultLabel: {
      markup: Markup.getForeignObjectMarkup(),
      attrs: {
        fo: {
          width: 120,
          height: 30,
          x: 0,
          y: 0
        }
      }
    },
    label: {
      position: 0.25
    },
    attrs: {
      line: {
        stroke: '#ccc'
      }
    },
    tools: [
      {
        name: 'tooltip',
        args: {
          tooltip: 'Top Left 提示文字'
        }
      }
    ]
  },
  true
)

// 定义添加节点
const addNode = () => {
  graph.value.addNode({
    shape: 'custom-node',
    x: 0,
    y: 0,
    width: 150,
    height: 100,
    label: '我是新添加的节点'
  })
}

const knob = ref(null)

const TooltipTool = {
  props: ['edgeView', 'tooltip'],
  mounted () {
    knob.value = document.createElement('div')
    this.$el.appendChild(knob.value)
    knob.value.style.position = 'absolute'
    this.bindEvents()
  },
  methods: {
    bindEvents () {
      this.edgeView.on('mouseenter', this.onMouseEnter)
      this.edgeView.on('mouseleave', this.onMouseLeave)
      this.edgeView.on('mousemove', this.onMouseMove)
    },
    onMouseEnter (event) {
      this.updatePosition(event)
      this.toggleTooltip(true)
    },
    onMouseLeave () {
      this.updatePosition()
      this.toggleTooltip(false)
    },
    onMouseMove () {
      this.updatePosition()
      this.toggleTooltip(false)
    },
    toggleTooltip (visible) {
      if (visible) {
        const tooltipContent = `<div><el-tooltip class="item" effect="dark" content="${this.tooltip}" placement="top-start"></el-tooltip></div>`
        this.$el.innerHTML = tooltipContent
      } else {
        this.$el.innerHTML = ''
      }
    },
    updatePosition (event) {
      if (event) {
        const p = this.edgeView.graph.clientToGraph(
          event.clientX,
          event.clientY
        )
        knob.value.style.display = 'block'
        knob.value.style.left = `${p.x}px`
        knob.value.style.top = `${p.y}px`
      } else {
        knob.value.style.display = 'none'
        knob.value.style.left = '-1000px'
        knob.value.style.top = '-1000px'
      }
    }
  },
  beforeUnmount () {
    this.edgeView.off('mouseenter', this.onMouseEnter)
    this.edgeView.off('mouseleave', this.onMouseLeave)
    this.edgeView.off('mousemove', this.onMouseMove)
  }
}

// 生命周期
onMounted(() => {
  initGraph()
})

// 按钮点击添加节点
const addEntity = e => {
  const node = graph.value.createNode({
    shape: 'custom-node'
  })
  dnd.value.start(node, e)
}

const onClick = () => {
  alert('clicked')
}

register({
  shape: 'custom-vue-node',
  width: 100,
  height: 100,
  component: ProgressNode
})
const TeleportContainer = getTeleport()
</script>

<style lang="scss" scoped></style>
